package socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 聊天案例服务端
 */
public class Server {
    private ServerSocket serverSocket;
    private List<ClientHandler> clients = new ArrayList<>();

    public Server() {
        try {
            System.out.println("正在启动服务端...");
            serverSocket = new ServerSocket(8088);
            System.out.println("服务端启动成功，等待客户端连接...");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start() {
        try {
            while (true) {
                Socket socket = serverSocket.accept();
                System.out.println("客户端已连接: " + socket.getInetAddress());

                ClientHandler handler = new ClientHandler(socket);
                clients.add(handler);
                new Thread(handler).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private class ClientHandler implements Runnable {
        private Socket socket;
        private InputStream in;
        private OutputStream out;
        private String clientName;

        public ClientHandler(Socket socket) {
            this.socket = socket;
            try {
                in = socket.getInputStream();
                out = socket.getOutputStream();
                // 可以在这里实现客户端命名逻辑
                clientName = "客户端" + socket.getPort();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void run() {
            try {
                while (true) {
                    // 读取消息长度
                    int length = in.read();
                    if (length == -1) {
                        // 客户端关闭连接
                        break;
                    }

                    // 读取消息内容
                    byte[] buffer = new byte[length];
                    int bytesRead = 0;
                    while (bytesRead < length) {
                        int count = in.read(buffer, bytesRead, length - bytesRead);
                        if (count == -1) {
                            break;
                        }
                        bytesRead += count;
                    }

                    if (bytesRead == length) {
                        String message = new String(buffer, StandardCharsets.UTF_8);
                        System.out.println(clientName + ": " + message);
                        broadcast(clientName + ": " + message, this);
                    }
                }
            } catch (IOException e) {
                // 客户端断开连接
            } finally {
                try {
                    socket.close();
                    clients.remove(this);
                    System.out.println(clientName + " 已断开连接");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        private void broadcast(String message, ClientHandler sender) {
            for (ClientHandler client : clients) {
                if (client != sender) {
                    try {
                        byte[] data = message.getBytes(StandardCharsets.UTF_8);
                        client.out.write(data.length);
                        client.out.write(data);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public static void main(String[] args) {
        Server server = new Server();
        server.start();
    }
}